package com.wuhuahe.luanfeng.netty.example.rpc;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * Created By wuhuahe
 * author:游龙
 * Date: 2018-07-14
 * Time: 16:39
 * Desc:
 */
public class ServerHandler extends SimpleChannelInboundHandler<RpcRequest> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServerHandler.class);
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequest request) throws Exception {
        RpcResponse response = new RpcResponse();
        LOGGER.info("server read:" + request.toString());
        response.setId(request.getId());
        try {
            Object result = invoke(request);
            response.setResult(result);
        } catch (Exception e) {
            response.setException(e);
        }
        ctx.writeAndFlush(response);
        LOGGER.info("server send:" + response.toString());
    }

    public Object invoke(RpcRequest request) throws Exception {
        String classname = request.getClassName();
        String methodname = request.getMethodName();
        Class<?>[] parameterTypes = request.getParameterTypes();
        Object[] parameters = request.getParameters();

        Object o = ServiceMng.getService(classname);
        Class clazz = o.getClass();
        Method method = clazz.getMethod(methodname, parameterTypes);
        Object result = method.invoke(o, parameters);
        return result;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        LOGGER.error("server caught exception", cause);
        ctx.close();
    }
}
